/**
 * 权限配置文件
 * @author Gray
 */
 import router from './router'
 import store from './store'
 import NProgress from 'nprogress' // progress bar
 import 'nprogress/nprogress.css' // progress bar style
 import { Message } from 'element-ui'
 import { getToken } from '@/utils/token' // get token from cookie
//  import { flatteningArray } from '@/utils'
 
 NProgress.configure({ showSpinner: false }) // NProgress Configuration
 
 const whiteList = ['/login'] // 白名单路由
 
 const checkAuth = (route) => {
  if (route.meta.needToken) {
    return getToken()
  } else {
    return true
  }
 }
 
 router.beforeEach(async(to, from, next) => {
   // start progress bar
   NProgress.start()
   if (whiteList.indexOf(to.path) < 0) {
     // determine whether the user has logged in
    const hasToken = getToken()
    if (hasToken) {
      if (!store.state.user.userInfo) {
        store.dispatch('user/setUserInfo')
      }
      if (to.fullPath.indexOf('loginIndex') >= 0) {
        NProgress.done()
        next('/')
      } else {
        NProgress.done()
        next()
      }
    } else {
      if (!checkAuth(to)) {
        Message({
          message: '请先登录！',
          type: 'error',
          duration: 5 * 1000
        })
        NProgress.done()
        next('/')
      } else {
        NProgress.done()
        next()
      }
    }
   } else {
    NProgress.done()
    next()
   }
  
 })
 
 router.afterEach(() => {
   // finish progress bar
   NProgress.done()
 })
 